.PHONY: all moon planet build protos stat cert ca theMoon thePlanet

BUILD_TIME = $(shell date -R)
GIT_COMMIT = $(shell git rev-parse --short HEAD)
GO_VERSION = $(word 3, $(shell go version))
OS_ARCH    = $(word 4, $(shell go version))

MOON_TARGET = "theMoon"
PLANET_TARGET = "thePlanet"
CERTTOOL = ./authentication/tool/gen.go
CERTDIR = ./cert

all:
	@$(MAKE) moon --no-print-directory
	@$(MAKE) planet --no-print-directory

## moon: 编译生成theMoon
moon: TARGET:=theMoon
moon: SOURCE:=./moon/cmd
moon: theMoon stat

## planet: 编译生成thePlanet
planet: TARGET:=thePlanet
planet: SOURCE:=./planet/cmd
planet:thePlanet stat

## run-moon: 编译并运行moon
run-moon: moon
	@./$(MOON_TARGET)

## run-planet: 编译并运行planet
run-planet: planet
	@./$(PLANET_TARGET)

## clean: 清理编译缓存与二进制文件
clean:
	go clean --cache -i ./moon/cmd
	go clean --cache -i ./planet/cmd
	@if [ -f $(MOON_TARGET) ]; then rm $(MOON_TARGET); fi
	@if [ -f $(PLANET_TARGET) ]; then rm $(PLANET_TARGET); fi

## protos: 编译项目内的proto文件
protos:
	cd radio/protos && protoc --gofast_out=. *.proto

stat:
	@echo "生成文件大小: " $(shell echo "scale=3; $(shell stat -c %s $(TARGET))/1024/1024" |bc) "MB"


thePlanet:
	go build -v -ldflags \
          "-X 'github.com/Unixeno/TheMoon/planet.GitCommit=${GIT_COMMIT}'\
          -X 'github.com/Unixeno/TheMoon/planet.GoVersion=${GO_VERSION}' \
          -X 'github.com/Unixeno/TheMoon/planet.OSArch=${OS_ARCH}' \
          -X 'github.com/Unixeno/TheMoon/planet.BuildTime=${BUILD_TIME}'" -o  $(TARGET) $(SOURCE)
theMoon:
	go build -v -o $(TARGET) $(SOURCE)

ifneq (, $(wildcard cert/ca.pem))
ca:
	@echo "ca证书已存在, 若要重新生成证书, 请先make cleanca清理证书"
else
ca:
	go run $(CERTTOOL) -ca -out $(CERTDIR)/ca.pem -keyout $(CERTDIR)/ca.key $(KEYTYPE)
endif

type=
ifdef type
	KEYTYPE := -type $(type)
endif

ifndef node
cert:
	@echo "生成证书时必须指定node参数"
cert-server:
	@echo "生成服务端证书时必须指定node参数"
else
cert:
	@go run $(CERTTOOL) -out $(CERTDIR)/moon.pem -keyout $(CERTDIR)/moon.key $(KEYTYPE) -cain $(CERTDIR)/ca.pem \
		-cakey $(CERTDIR)/ca.key -node $(node)
cert-server:
	go run $(CERTTOOL) -out $(CERTDIR)/planet.pem -keyout $(CERTDIR)/planet.key $(KEYTYPE) -cain $(CERTDIR)/ca.pem \
		-cakey $(CERTDIR)/ca.key -node $(node)
endif


## cleanca: 清理ca证书文件
cleanca:
	rm -vf $(CERTDIR)/ca.key $(CERTDIR)/ca.pem

## cleancert: 清理证书文件
cleancert:
	find $(CERTDIR) -type f -not -name 'ca.*' -delete -print

## help: 显示此帮助信息
help: Makefile
	@echo "选择一个命令来执行"
	@sed -n 's/^##//p' $< | sed 's/^/make/' | column -t -s ':' |  sed -e 's/^/ /'

## apidoc: 生成项目文档
apidoc:
	swagger generate spec -m -o ./swagger.yml -w planet
